<template>
    <div class="app-container">
      <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
      <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
      </el-table>
    </div>
  </template>
  
  <script>
  import UploadExcelComponent from '@/components/UploadExcel/index.vue'
  import { addEmployeeBatch } from '@/api/employees'
  
  export default {
    name: 'UploadExcel',
    components: { UploadExcelComponent },
    data() {
      return {
        tableData: [],
        tableHeader: []
      }
    },
    methods: {
      beforeUpload(file) {
        const isLt1M = file.size / 1024 / 1024 < 1
  
        if (isLt1M) {
          return true
        }
  
        this.$message({
          message: 'Please do not upload files larger than 1m in size.',
          type: 'warning'
        })
        return false
      },
      handleSuccess({ results, header }) {
        this.tableData = results
        this.tableHeader = header
        // console.log(results,header);
        // 1. 读取数据
        // 2. 将数据格式化
       const data =  this.transExcel(results)
        // 3. 发送axajx
        this.doAdd(data)
      },
      // 实现批量导入
      async doAdd (data){
        try {
          const res = await addEmployeeBatch(data)
          this.$router.back()
          console.log('addEmployeeBatch', res)
          // 保存数据 
        } catch (err) {
          console.log('addEmployeeBatch', err)
        }
      },
      // 定义中文转英文
      transExcel(data) {
            // 准备一个对应的键值转换
            const mapInfo = {
                '入职日期': 'timeOfEntry',
                '手机号': 'mobile',
                '姓名': 'username',
                '转正日期': 'correctionTime',
                '工号': 'workNumber',
                '部门': 'departmentName',

            }
            
            return data.map(zhObj => {
                // zhObj==>  {
                // 入职日期: 44505,
                // 姓名: "小张",
                // 工号: "9002",
                // 手机号: "13800000252",
                // 转正日期: 44892,
                // 部门: "总裁办"
            // },
                const enObj = {}   // 存储英文的key的数据  {'timeOfEntry': 44505}
                const zhKeys = Object.keys(zhObj) //['入职日期', '姓名', '工号', '手机号', '转正日期', '部门']

                zhKeys.forEach(zhKey => {
                    // 根据中文的key获取到英文的key
                    const enKey = mapInfo[zhKey]

                    enObj[enKey] = zhObj[zhKey]
                })

                return enObj
            })
        }
    },
      
  }
  </script>
  